<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Builder;

class ExistsInApplication implements ValidationRule, DataAwareRule
{
    protected array $data = [];

    public function __construct(protected string $model, protected string $field, protected string $name)
    {
    }

    public function setData(array $data): static
    {
        $this->data = $data;

        return $this;
    }

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!isset($this->data['app_key'])) {
            $fail('【'.$this->name.'】缺少APP_KEY');

            return;
        }

        $model = resolve($this->model);

        if (!method_exists($model, 'application')) {
            $fail('【'.$this->name.'】不支持此操作');

            return;
        }

        $exists = $model
            ->whereHas('application', function (Builder $query) {
                $query->where('app_key', $this->data['app_key']);
            })->where($this->field, $value)
            ->exists();

        if (!$exists) {
            $fail('【'.$this->name.'】不存在');
        }
    }
}
